export default {
    /**
     * 登录状态
     * @returns {boolean}
     */
    loggedIn() {
        return !!localStorage.token
    },
    /**
     * 更改登录状态
     */
    onChangeStatus() {
    },

    /**
     * 登录函数
     * @param email
     * @param password
     * @returns {Promise<unknown>}
     */
    login(email, password) {
        return new Promise((resolve, reject) => {
            if (localStorage.token) {
                this.onChangeStatus(true)
            }
            mockRequest(email, password).then(res => {
                if (res.authenticated) {
                    localStorage.token = res.token;
                    this.onChangeStatus(true);
                    resolve({code: 200, msg: '登录成功', data: res.token})
                } else {
                    this.onChangeStatus(false);
                    resolve({code: 403, msg: '用户名密码不正确', data: ''})
                }
            }).catch(err => {
                console.log(err);
                reject(err);
            })
        })
    },

    /**
     * 登出函数
     */
    logout() {
        delete localStorage.token;
        this.onChangeStatus(false);
    }


}

/**
 * 模拟后端
 * @param email 邮箱
 * @param password 密码
 * @returns {Promise<unknown>}
 */
function mockRequest(email, password) {
    return new Promise((resolve, reject) => {
        try {
            if (email === 'focuxin@qq.com' && password === '123') {
                resolve({
                    authenticated: true,
                    token: Math.random().toString(36).substring(7)
                })
            } else {
                resolve({
                    authenticated: false
                })
            }
        } catch (e) {
            reject(e)
        }
    })
}